import axios from "axios";
import {Loading, Message} from 'element-ui'
import store from '../store'
export function request(config) {
  const instance = axios.create({
    //根路径
    baseURL: store.state.baseURL,
    timeout: 10000,
  })
  //开始加载动画
  let loading;

  function startLoading() {
    loading = Loading.service({
      lock: true, //是否锁定
      text: '拼命加载中...',//加载中需要显示的文字
      /* background:'rgba(0,0,0,0.2)',//背景颜色*/
    });
  }

  //结束加载动画
  function endLoading() {
    loading.close();
  }
  //不加在动画的url
  const animationUrl = ['/captcha'];
  //axios 拦截器
  //请求拦截
  instance.interceptors.request.use(config => {
    if(animationUrl.indexOf(config.url) === -1){
      startLoading();//请求时的加载动画
    }
    //每个请求头文件加入 token
    config.headers.token = window.localStorage.getItem('token');
    console.log("restoken: " + config.headers.token)
    return config
  }, err => {
    console.log(err)
  })

  //响应拦截
  instance.interceptors.response.use(res => {
    const token = res.data.data.token;
    console.log("token:"  + token);
    if (token != null) {
      window.localStorage.setItem('token', token);
    }
    if (res.data.code !== 200) {
      Message({
        message: '操作失败，请稍后再试！',
        type: 'error',
        duration: 3 * 1000
      })
    }
    if(animationUrl.indexOf(config.url) === -1){
      setTimeout(res => {
        endLoading()//结束动画
      })
    }
    return res.data
  }, err => {
    if(animationUrl.indexOf(config.url) === -1){
      endLoading()//结束动画
    }
/*    if (err.toString().indexOf("Request failed with status code 401") >= 0) {
      MessageBox.confirm('您已被登出', '登出提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'2
      }).then(r => {
        let href = window.location.href;
        window.location.href = href.substring(0, href.indexOf("/")) + "/login"
      });
    } else {
      MessageBox.confirm('服务器连接失败', '错误', {
        confirmButtonText: '刷新页面',
        cancelButtonText: '取消',
        type: 'error'
      }).then(r => {
        window.location.reload()
      });
    }*/
  })
  // 发送真正的网络请求
  return instance(config)
}
